﻿using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.Extensions.Others;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.CommonModel;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.ParamModels;
using XiangziProjectTemplete.Core.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using XiangziProjectTemplete.Core.Model.ViewModels.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Common.Helper;
using System.Linq;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// 用户站点绑定查询视图 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class V_UserStationController : ControllerBase
    {
        private readonly IV_UserStationServices _V_UserStationServices;
        private readonly IUser _user;
        private readonly ILogger<V_UserStationController> _logger;
        private readonly IBase_UserStationServices _base_UserStationServices;
        readonly ISysUserInfoServices _sysUserInfoServices;
        private readonly IBase_StationServices _base_StationServices;


        public V_UserStationController(
            IBase_StationServices base_StationServices,
             ISysUserInfoServices sysUserInfoServices,
            IBase_UserStationServices base_UserStationServices,
            IV_UserStationServices V_UserStationServices, IUser user, ILogger<V_UserStationController> logger)
        {
            this._base_StationServices = base_StationServices;
            _sysUserInfoServices = sysUserInfoServices;
            _V_UserStationServices = V_UserStationServices;
            _user = user;
            _logger = logger;
            _base_UserStationServices = base_UserStationServices;
        }

        /// <summary> 
        /// 分页获取用户站点查询视图列表 
        /// </summary> 
        /// <param name="param">筛选条件</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        public async Task<MessageModel<PageModel<V_UserStationViewModel>>> Get([FromBody] V_UserStationParam param)
        {
            if (string.IsNullOrEmpty(param.searchVal) || string.IsNullOrWhiteSpace(param.searchVal))
            {
                param.searchVal = string.Empty;
            }

            var whereConditions = WhereConditionsExtensions.GetWhereConditions<V_UserStation, V_UserStationParam>(param);
            if (!whereConditions.IsSuccess)
            {
                return new MessageModel<PageModel<V_UserStationViewModel>>()
                {
                    msg = whereConditions.ErrMsg,
                    success = false,
                    response = null
                };
            }
            var data = await _V_UserStationServices.QueryPage(whereConditions.data, param.page, param.pageSize, " ModifyTime desc ");
            //转换
            var newQueryData = ListHelper.T1ToT2<PageModel<V_UserStation>, PageModel<V_UserStationViewModel>>(data);
            if (newQueryData.data != null && newQueryData.data.Count > 0)
            {
                foreach (var item in newQueryData.data)
                {
                    await GetBindStationList(item);
                }
            }
            return new MessageModel<PageModel<V_UserStationViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = newQueryData
            };

        }


        private async Task<V_UserStationViewModel> GetBindStationList(V_UserStationViewModel item)
        {
            //处理站点的绑定
            if (!string.IsNullOrEmpty(item.BindStationListStr))
            {
                item.BindStationList = JsonConvert.DeserializeObject<List<int[]>>(item.BindStationListStr);

                //var bb=item.BindStation.Split(",");
                //List<int> stationIdList = new List<int>();
                //foreach (var b in bb)
                //{
                //    stationIdList.Add(Convert.ToInt32(b));
                //}
                //var codeList = await _base_StationServices.Query();
                //var list = codeList.Where(d => stationIdList.Contains(d.Id)).Select(d => d.StationName).ToList();
               // item.Str_BigMaterialStations = string.Join(",", list);
            }
            return item;
        }


        /// <summary> 
        /// 获取单个用户站点查询视图 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public async Task<MessageModel<V_UserStation>> Get(int id = 0)
        {
            return new MessageModel<V_UserStation>()
            {
                msg = "获取成功",
                success = true,
                response = await _V_UserStationServices.QueryById(id)
            };
        }


        /// <summary> 
        /// 更新用户站点查询视图 
        /// </summary> 
        /// <param name="request">要更新的用户站点查询视图对象</param> 
        /// <returns>更新结果</returns> 
        [HttpPut]
        public async Task<MessageModel<string>> Put([FromBody] V_UserStationViewModel request)
        {
            try
            {
                #region 验证 
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<V_UserStation, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>()
                {
                     new ValidateModel(){ ChinaName="用户ID",PropertyName="uID" },
                };
                retBody = ValidateDataHelper.CommonValidate<V_UserStation, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                #endregion

                string insertStr = "";
                if (request.BindStationList != null && request.BindStationList.Count > 0)
                {
                    foreach (var item in request.BindStationList)
                    {
                        int[] arr = item;
                        insertStr += arr[1] + ",";
                    }
                    insertStr = insertStr.Substring(0, insertStr.Length - 1);
                }

                var dbObjs = await _base_UserStationServices.Query(x => x.uID == request.uID);
                if (dbObjs == null || dbObjs.Count == 0)
                {
                    var userInfo = await _sysUserInfoServices.QueryById(request.uID);
                    Base_UserStation insert_UserStation = new Base_UserStation();
                    insert_UserStation.CreateTime = insert_UserStation.ModifyTime = DateTime.Now;
                    insert_UserStation.CreateBy = insert_UserStation.ModifyBy = _user.Name;
                    insert_UserStation.CreateId = insert_UserStation.ModifyId = _user.ID;
                    insert_UserStation.OperationRemark = "新增";
                    insert_UserStation.Remark = request.Remark;

                    insert_UserStation.BindStation = insertStr;
                    insert_UserStation.BindStationListStr = JsonConvert.SerializeObject(request.BindStationList);

                    insert_UserStation.uID = request.uID;
                    insert_UserStation.uLoginName = userInfo.uLoginName;


                    await _base_UserStationServices.Add(insert_UserStation);
                }
                else if (dbObjs.Count > 1)
                {
                    return MessageModel<string>.Fail("数据存在" + dbObjs.Count + "条，请联系管理员!");
                }
                else
                {
                    var dbObj = dbObjs[0];
                    dbObj.ModifyTime = DateTime.Now;
                    dbObj.ModifyBy = _user.Name;
                    dbObj.ModifyId = _user.ID;
                    dbObj.OperationRemark = "更新";
                    dbObj.Remark = request.Remark;

                    dbObj.BindStation = insertStr;
                    dbObj.BindStationListStr = JsonConvert.SerializeObject(request.BindStationList);

                    await _base_UserStationServices.Update(dbObj);
                }
                return MessageModel<string>.Success("更新成功", request.Id.ObjToString());
            }
            catch (Exception ex)
            {
                _logger.LogError("更新用户站点查询视图出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<string>.Fail("更新用户站点查询视图出现异常:" + ex.Message);
            }
        }
    }
}
